<!DOCTYPE html>
<html>
    <head>
        <meta name="mobile-web-app-capable" content="yes">
        <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1"/>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="../../script/semantic/semantic.min.css">
        <script src="../../script/jquery.min.js"></script>
        <script src="../../script/semantic/semantic.min.js"></script>
        <script src="../../script/ao_module.js"></script>
        <script type="text/javascript" src="../../script/applocale.js"></script>
        <link rel="stylesheet" href="../../script/ao.css">
        <style>

            body{
                background-color: var(--body_background);
            }

            body.darkTheme .ui.tabular.menu .active.item{
                background: var(--body_background_active) !important;
                border-color: transparent;
                border-top-left-radius: 0 !important;
                border-top-right-radius: 0 !important;
            }

            body.darkTheme .ui.tabular.menu{
                border-bottom: 1px solid var(--divider) !important;
            }

            body.darkTheme .ui.selection.dropdown{
                background-color: var(--body_background_secondary);
            }

            .ui.tabular.menu .item:hover{
                background-color: var(--body_background_secondary);
            }

            .ui.tabular.menu .item{
                cursor: pointer;
            }

            .hidden{
                display:none;
            }

            .backgroundpreview{
                border: 1px solid #898989;
            }

            .colorpallete{
                border: 1px solid transparent;
                cursor: pointer;
            }

            .colorpallete:hover{
                border: 1px solid white;
            }

        </style>
    </head>
    <body>
        <div class="ui small tabular menu" style="position:fixed; top:0em; left:0px; width: 100%;">
            <div class="active item" data-tab="wallpaper" locale="menu/wallpaper">Wallpaper</div>
            <div class="item" data-tab="sound" locale="menu/sound">Sound</div>
            <div class="item" data-tab="theme" locale="menu/theme">Theme</div>
            <div class="item" data-tab="advance" locale="menu/advance">Advance</div>
        </div>
        <div style="position:fixed; top: calc(0em + 42px); left:0px; width: 100%; height: calc(100% - 42px); overflow-y:auto;">
            <div class="ui active tab" data-tab="wallpaper">
                <!-- Wallpaper Functions -->
                <br>
                <div class="ui container">
                    <h3 class="ui header">
                        <i class="image outline icon"></i>
                        <div class="content">
                            <span locale="wallpaper/title">Wallpapers</span>
                            <div locale="wallpaper/desc" class="sub header">Manage your desktop preferences</div>
                        </div>
                    </h3>
                    <div class="ui divider"></div>

                    <div class="ui grid">
                        <div class="ten wide column">
                            <img id="mainBackground" class="ui fluid image backgroundpreview" src="">
                        </div>
                        <div class="six wide column">
                            
                        </div>
                    </div>
                
                    <div class="ui divider"></div>
                    <div id="backgroundPreviewList" class="ui grid">
                        <div class="four wide column">
                            <img class="ui fluid image backgroundpreview" src="">
                        </div>
                        <div class="four wide column">
                            <img class="ui fluid image backgroundpreview" src="">
                        </div>
                        <div class="four wide column">
                            <img class="ui fluid image backgroundpreview" src="">
                        </div>
                        <div class="four wide column">
                            <img class="ui fluid image backgroundpreview" src="">
                        </div>
                    </div>

                    <div class="ui divider"></div>
                    <h4 class="ui header">
                        <span locale="wallpaper/title">Background Wallpaper</span>
                        <div locale="wallpaper/desc" class="sub header">Set your desktop background wallpaper theme.</div>
                    </h4>
                    <select id="wallpaperlist" class="ui fluid dropdown allowSelectDefaultThemes" onchange="handleBackgroundSelectionChange(this.value);">
                        <option value="" locale="wallpaper/option/title">Wallpaper Packs</option>
                    </select>
                    <small locale="wallpaper/option/desc">This option will be disabled by default if you have set your "User Defined Wallpaper" in Advance tab.</small>
                    <br> <br>
                    <button class="ui small green right floated button allowSelectDefaultThemes" onclick="applyWallpaper();" locale="wallpaper/option/apply"><i class="checkmark icon"></i> Apply Wallpaper</button>
                    <br><br><br>
                    <div class="ui green inverted segment" style="display:none" id="wallpaperChangeConfirm">
                        <h4 class="ui header">
                            <i class="check circle icon"></i>
                            <div class="content">
                            <span locale="wallpaper/option/updated">Wallpaper Updated</span>
                            <div class="sub header" locale="wallpaper/option/updateddesc">You should be seeing your desktop wallpaper change in a moment.</div>
                            </div>
                        </h4>
                    </div>

                    <!-- Wallpaper change interval-->
                    <div class="ui divider"></div>
                    <h4 class="ui header">
                        <span locale="wallpaper/option/interval">Wallpaper Interval</span>
                        <div class="sub header" locale="wallpaper/option/intervaldesc">Set the interval between the wallpaper image cycles.</div>
                    </h4>
                    <select id="changeInterval" class="ui fluid dropdown" onchange="handleIntervalChange(this.value);">
                        <option value="10" locale="wallpaper/interval/10s">10 seconds</option>
                        <option value="30" locale="wallpaper/interval/30s">30 seconds</option>
                        <option value="60" locale="wallpaper/interval/60s">60 seconds</option>
                        <option value="180" locale="wallpaper/interval/3min">3 minutes</option>
                        <option value="300" locale="wallpaper/interval/5min">5 minutes</option>
                        <option value="600" locale="wallpaper/interval/10min">10 minutes</option>
                        <option value="1800" locale="wallpaper/interval/30min">30 minutes</option>
                        <option value="3600" locale="wallpaper/interval/1h">1 hour</option>
                    </select>

                    <div class="ui green inverted segment" style="display:none" id="interfaceChangeConfirm">
                        <h4 class="ui header">
                            <i class="check circle icon"></i>
                            <div class="content">
                            <span locale="wallpaper/interval/succ">Wallpaper Interval Updated</span>
                            <div class="sub header" locale="wallpaper/interval/succdesc">This setting will only apply to this browser</div>
                            </div>
                        </h4>
                    </div>
                </div>
                <br><br><br>
            </div>
            <div class="ui tab" data-tab="sound">
                <br>
                <div class="ui container">
                    <h3 class="ui header">
                        <i class="music icon"></i>
                        <div class="content">
                            <span locale="sound/title">System Sound</span>
                            <div class="sub header" locale="sound/desc">Customize system sound effect</div>
                        </div>
                    </h3>
                    <div class="ui divider"></div>
                    <h4 class="ui header">
                        <span locale="sound/custom/title">Custom Startup Sound</span>
                        <div class="sub header" locale="sound/custom/desc">User defined startup sound to play when login to the web desktop</div>
                    </h4>
                    <h3 id="userSelectedStartupSound" locale="sound/custom/disable">Disabled</h3>
                    <button class="ui small basic right floated button" onclick="clearStartupAudioSelection()"><i class="red remove icon"></i> <span locale="sound/custom/clear">Clear Selection</span></button>
                    <button class="ui small basic right floated button" onclick="selectStartupAudio();"><i class="yellow folder open icon"></i> <span locale="sound/custom/select">Select File</span></button>
                    <br><br>
                    <div class="ui divider"></div>
                </div>
            </div>
            <div class="ui tab" data-tab="theme">
                <!-- Theme Color Related !-->
                <br>
                <div class="ui container">
                    <h3 class="ui header">
                        <i class="paint brush icon"></i>
                        <div class="content">
                            <span locale="themecolor/title">Theme Color</span>
                            <div class="sub header" locale="themecolor/desc">Change the system theme color settings</div>
                        </div>
                    </h3>

                    <div class="ui divider"></div>
                    <div class="ui container">
                        <div id="colorgrid">
                            Loading...
                        </div>
                    </div>
                    <br>
                    <div class="ui divider"></div>
                    <button class="ui small basic black button" onclick="restoreDefaultThemeColor();" locale="themecolor/color/Default">Restore Default</button>
                    <br><br><br>
                    
                </div>
            </div>
            <div class="ui tab" data-tab="advance">
                <!-- Advance User Customization !-->
                <br>
                <div class="ui container">
                    <h3 class="ui header">
                        <i class="setting icon"></i>
                        <div class="content">
                            <span locale="advance/title">Advance Customization</span>
                            <div class="sub header" locale="advance/desc">Manage your desktop preferences</div>
                        </div>
                    </h3>
                    <div class="ui divider"></div>
                    <h4 class="ui header">
                        <i class="image icon" style="display:inline-block;"></i> <span locale="advance/wallpaper/title">User Defined Wallpaper</span>
                        <div class="sub header" locale="advance/wallpaper/desc">Advanced user customization function for desktop interface</div>
                    </h4>
                    <h3 id="userSelectedFolderPath" locale="advance/wallpaper/disabled">Disabled</h3>
                    <p locale="advance/wallpaper/reminder">If you have set a folder for loading desktop wallpapers, the image files from that folder will be used instead of the system build in wallpapers.</p>
                    <button class="ui small basic right floated button" onclick="clearUserSelectedFolder();"><i class="red remove icon"></i><span locale="advance/wallpaper/clear">Clear Selection</span></button>
                    <button class="ui small basic black right floated button" onclick="selectUserFolder();"><i class="yellow folder open icon"></i> <span locale="advance/wallpaper/select">Select Folder</span></button>
                    <br><br>
                    
                    <div class="ui divider"></div>
                    <h4 class="ui header">
                        <i class="external square alternate icon" style="display:inline-block;" ></i> <span locale="advance/mobile/shorcut/title">Mobile Desktop Shortcuts</span>
                        <div class="sub header" locale="advance/mobile/shorcut/subtitle">Change the default four shortcuts for mobile desktop interface</div>
                    </h4>
                    <p locale="advance/mobile/shorcut/instruction">Please pick your shortcut from left to right</p>
                    <div>
                        <div class="ui fluid search selection moduledropbox dropdown">
                            <input type="hidden" id="shortcut1">
                            <i class="dropdown icon"></i>
                            <div class="default text" locale="advance/mobile/shorcut/shortcut/1">Shortcut 1</div>
                            <div class="webapplist menu">
                            
                            </div>
                        </div>
                        <br>
                        <div class="ui fluid search selection moduledropbox dropdown">
                            <input type="hidden" id="shortcut2">
                            <i class="dropdown icon"></i>
                            <div class="default text" locale="advance/mobile/shorcut/shortcut/2">Shortcut 2</div>
                            <div class="webapplist menu">
                            
                            </div>
                        </div>
                        <br>
                        <div class="ui fluid search selection moduledropbox dropdown">
                            <input type="hidden" id="shortcut3">
                            <i class="dropdown icon"></i>
                            <div class="default text" locale="advance/mobile/shorcut/shortcut/3">Shortcut 3</div>
                            <div class="webapplist menu">
                                
                            </div>
                        </div>
                        <br>
                        <div class="ui fluid search selection moduledropbox dropdown">
                            <input type="hidden" id="shortcut4">
                            <i class="dropdown icon"></i>
                            <div class="default text" locale="advance/mobile/shorcut/shortcut/4">Shortcut 4</div>
                            <div class="webapplist menu">
                            
                            </div>
                        </div>
                    </div>
                    <br>
                    <button class="ui small green right floated button" onclick="saveShortcuts();"  locale="advance/mobile/shorcut/save"><i class="checkmark icon"></i> Save Shortcuts</button>
                    <br><br>
                    <div class="ui green inverted segment" style="display:none" id="shortcutChangeSaved">
                        <h4 class="ui header">
                            <i class="check circle icon"></i>
                            <div class="content">
                            <span locale="advance/mobile/shorcut/updated">Shorcuts Updated</span>
                            <div class="sub header" locale="advance/mobile/shorcut/updateddesc">Open the mobile interface via your phone to view the changes</div>
                            </div>
                        </h4>
                    </div>
                    
                </div>
                <br><br>
            </div>
        </div>
        <br><br>
        <script>
            var desktopThemeList = [];
            var isStartingUp = true;
            var cancelColorRestore = false; //If the user clicked on the target color pallete, do not restore the desktop to its original color before selection

            $(".dropdown").dropdown();
            $('.tabular.menu .item').tab();


            try{
                applocale.init("../locale/personalization.json", function(){
                    applocale.translate();
                    init();
                });
            }catch(ex){
                //fail to load localization file. Use default
                init()
            }
            

            function init(){
                //Startup process
                initDefaultBackgroundChangeValue();
                initUserDefinedWallpaperFolder(function(themeName){
                    initCurrentBackgroundPreview(themeName);
                });
                generateColorGrids();
                getStartupAudio();
                initModuleList();
                initTheme();
            }

           
            function initTheme(){
                //Load system theme
                $.get("../../system/file_system/preference?key=file_explorer/theme",function(data){
                    if (data.error === undefined){
                        if (data == "darkTheme"){
                            $("body").addClass("darkTheme");
                        }else{
                            $("body").addClass("whiteTheme");
                        }
                    }
                });
            }


            //Return the data stored in the theme settings
            //Will return either theme pack name or path for user defined folder
            function initUserDefinedWallpaperFolder(callback = undefined){
                $.get("../../system/desktop/theme?get=true", function(data) {
                    if (data.includes(":/")){
                        //This is a path
                        $("#userSelectedFolderPath").text(data);
                        $(".allowSelectDefaultThemes").addClass("disabled");
                    }else{
                        $("#userSelectedFolderPath").text(applocale.getString("advance/wallpaper/disabled", "Disabled"));
                    }

                    if (callback != undefined){
                        callback(data);
                    }
                    
                });
            }
            
            function initModuleList(){
                $.get("../../system/modules/list", function(data){
                    $(".webapplist").html('');
                    data.forEach(app => {
                        if (app.Group != "Interface Module" && app.Group != "IME" && app.StartDir != ""){
                            $(".webapplist").append(`<div class="item" data-value="${app.Name}">${app.Name}</div>`);
                        }
                    });

                    $(".moduledropbox").dropdown();

                    //Get selected preferences
                    readPreference("ao/mobile/shorcut/1", function(data){
                        if (data != ""){
                            $("#shortcut1").val(data);
                            $("#shortcut1").parent().dropdown("set selected", data);
                        }
                    });

                    readPreference("ao/mobile/shorcut/2", function(data){
                        if (data != ""){
                            $("#shortcut2").val(data);
                            $("#shortcut2").parent().dropdown("set selected", data);
                        }
                    });

                    readPreference("ao/mobile/shorcut/3", function(data){
                        if (data != ""){
                            $("#shortcut3").val(data);
                            $("#shortcut3").parent().dropdown("set selected", data);
                        }
                    });

                    readPreference("ao/mobile/shorcut/4", function(data){
                        if (data != ""){
                            $("#shortcut4").val(data);
                            $("#shortcut4").parent().dropdown("set selected", data);
                        }
                    });
                })
            }

            function saveShortcuts(){
                var sc1 = $("#shortcut1").val();
                var sc2 = $("#shortcut2").val();
                var sc3 = $("#shortcut3").val();
                var sc4 = $("#shortcut4").val();

                if (sc1 != ""){
                    writePreference("ao/mobile/shorcut/1", sc1);
                }

                if (sc2 != ""){
                    writePreference("ao/mobile/shorcut/2", sc2);
                }

                if (sc3 != ""){
                    writePreference("ao/mobile/shorcut/3", sc3);
                }

                if (sc4 != ""){
                    writePreference("ao/mobile/shorcut/4", sc4);
                }

                $("#shortcutChangeSaved").stop().finish().slideDown("fast").delay(3000).slideUp("fast", function(){
                    if (parent != undefined && parent.initShortcuts != undefined){
                        parent.initShortcuts();
                    }
                });
            }

            function initDefaultBackgroundChangeValue(){
                if (localStorage.getItem("ao/desktop/backgroundInterval") == null){
                    //No background interval set.
                    $("#changeInterval").dropdown("set selected", "30");
                }else{
                    //There is already a setting for background interval change. Use that instead
                    var changeInterval = localStorage.getItem("ao/desktop/backgroundInterval");
                    $("#changeInterval").dropdown("set selected", changeInterval);
                }
            }

            //Startup sound 
            function selectStartupAudio(){
                ao_module_openFileSelector(setStartupAudio, undefined,"file",{
                    filter: ["mp3", "aac", "ogg", "wav"]
                });
            }

            function setStartupAudio(filedata){
                var filename = filedata[0].filename;
                var filepath = filedata[0].filepath;
                $("#userSelectedStartupSound").text(filepath);
                $.ajax({
                    url: "../../system/desktop/preference",
                    method: "POST",
                    data: {preference: "startup-audio", value: filepath},
                    success: function(data){
                        console.log(data);
                    }
                });
            }

            function getStartupAudio(callback=undefined){
                $.ajax({
                    url: "../../system/desktop/preference",
                    method: "POST",
                    data: {preference: "startup-audio"},
                    success: function(data){
                        if (data != undefined && data != ""){
                            $("#userSelectedStartupSound").text(data);
                        }
                        
                        if (callback != undefined){
                            callback(data);
                        }else{
                            console.log(data);
                        }
                    }
                });
            }

            function clearStartupAudioSelection(){
                $.ajax({
                    url: "../../system/desktop/preference",
                    method: "POST",
                    data: {preference: "startup-audio", remove: "true"},
                    success: function(data){
                        $("#userSelectedStartupSound").text(applocale.getString("sound/disabled", "Disabled"));
                    }
                });
            }

            //Change the interval to the given 
            function handleIntervalChange(newInterval){
                //Show change finsihed
                if (isStartingUp){
                    //Ignore startup change
                    return;
                }

                //Save interval to localStorage
                localStorage.setItem("ao/desktop/backgroundInterval", newInterval)
                $("#interfaceChangeConfirm").slideDown('fast').delay(3000).slideUp('fast');

                //Restart desktop background changer interval
                if (ao_module_virtualDesktop){
                    console.log("Restarting desktop background changer interval")
                    if (parent.backgroundIntervalCounter){
                        parent.clearInterval(parent.backgroundIntervalCounter);
                    }
                    parent.initBackgroundSwitchingAnimation();
                }
                
            }

            function selectUserFolder(){
                ao_module_openFileSelector(folderSelected, undefined,"folder",false);
            }

            function folderSelected(filedata){
                for (var i=0; i < filedata.length; i++){
                    var filename = filedata[i].filename;
                    var filepath = filedata[i].filepath;

                    //Save the overwrite folder path
                    $("#userSelectedFolderPath").text(filepath);
                    $.get("../../system/desktop/theme?set=" + filepath, function(data) {
                         //Reload desktop background pack
                         if (ao_module_virtualDesktop){
                            parent.changeDesktopTheme(filepath);
                         }

                         //Disable change to system build in themes
                         $(".allowSelectDefaultThemes").addClass("disabled");

                         //Load the preview
                         initCurrentBackgroundPreview();
                    });
                }
            }

            function clearUserSelectedFolder(){
                //Clear user selected folder
                $.get("../../system/desktop/theme?set=default", function(data) {
                         //Reload desktop background pack
                         if (ao_module_virtualDesktop){
                            parent.changeDesktopTheme("default");
                         }

                        //Re-enable the default theme seelct
                        $(".allowSelectDefaultThemes").removeClass("disabled");
                        $("#userSelectedFolderPath").text(applocale.getString("advance/wallpaper/select", "Disabled"));

                        initUserDefinedWallpaperFolder();
                        initCurrentBackgroundPreview();
                    });
            }

            function initCurrentBackgroundPreview(){
                //Get the list of theme in the system
                $.get("../../system/desktop/theme", function(data) {
                    desktopThemeList = data;
                    //Generate the wallpaper list
                    $("#wallpaperlist").html("");
                    var deftaultData = "";
                    desktopThemeList.forEach(themepack => {
                        var encodedData = encodeURIComponent(JSON.stringify(themepack));
                        var themeName = themepack.Theme.charAt(0).toUpperCase() + themepack.Theme.slice(1);
                        $("#wallpaperlist").append(`<option value="${encodedData}">${themeName}</option>`);
                        if (themepack.Theme == "default"){
                            deftaultData = encodedData;
                        }
                    });

                    //Get the one the user is currently using
                    $.get("../../system/desktop/theme?get=true", function(data) {
                        //Get the user theme settings
                        $(".backgroundpreview").attr('src','../../img/desktop/bg/nobg.jpg');
                        

                        //Check if the theme is custom path
                        if (data.includes(":/")){
                            //Is path. Load path preview
                            $.get("../../system/desktop/theme?load=" + data, function(imagelist){
                                //Load background preview
                                loadBackgroundPreviewForCustomFolder(imagelist);
                                 //End of startup process
                                isStartingUp = false;
                            });
                        }else{
                            //Check if the theme exists
                            var themeExists = false;
                            var targetThemeObject;
                            desktopThemeList.forEach(theme => {
                                if (theme.Theme == data){
                                    //Theme exists
                                    themeExists = true;
                                    targetThemeObject = theme;
                                }
                            });

                            if (themeExists == false){
                                //This theme not exists. Do not load preview
                                $("#wallpaperlist").dropdown("set selected","Default");
                            }else{
                                loadBackgroundPreview(targetThemeObject);
                                var themeName = data.charAt(0).toUpperCase() + data.slice(1)
                                $("#wallpaperlist").dropdown("set selected",themeName);
                            }
                            
                            //End of startup process
                            isStartingUp = false;
                        }
                    });
                });
            }

            function loadBackgroundPreviewForCustomFolder(imageList){
                $("#backgroundPreviewList").html("");
                $("#mainBackground").attr("src","../../media/?file=" + imageList[0]);
                
                for (var i = 1; i < imageList.length; i++){
                    $("#backgroundPreviewList").append(`<div class="four wide column">
                        <img class="ui fluid image backgroundpreview" src="${"../../media/?file=" + imageList[i]}">
                    </div>`);
                }
            }

            function loadBackgroundPreview(targetThemeObject){
                $("#backgroundPreviewList").html("");
                var imageList = targetThemeObject.Bglist;
                $("#mainBackground").attr("src","../../img/desktop/bg/" + targetThemeObject.Theme + "/" + imageList[0]);
                
                for (var i = 1; i < imageList.length; i++){
                    $("#backgroundPreviewList").append(`<div class="four wide column">
                        <img class="ui fluid image backgroundpreview" src="${"../../img/desktop/bg/" + targetThemeObject.Theme + "/" + imageList[i]}">
                    </div>`);
                }
            }

            function handleBackgroundSelectionChange(value){
                var targetThemeObject = JSON.parse(decodeURIComponent(value));
                loadBackgroundPreview(targetThemeObject);
            }

            function generateColorGrids(){
                $("#colorgrid").html("");
                $.getJSON("./colors.json", function(data){
                    for (let key in data) {
                        let colorcodes = data[key];
                        let thisSection = '';
                        let thisColorKey = key.charAt(0).toUpperCase() + key.slice(1);
                        thisSection += (`<div class="ui grid">`);
                        thisSection += (`<div class="five wide column">
                            ${applocale.getString("themecolor/color/" + thisColorKey, thisColorKey)}
                        </div>`);
                        for (let colorIndex in colorcodes) {
                            if (colorIndex < 300){
                                //Skip all the light colors
                                continue;
                            }
                            let colorHexCoxde = colorcodes[colorIndex];
                            thisSection += (`<div class="one wide column colorpallete" hex="${colorHexCoxde}" material="${colorIndex}" style="background-color: ${colorHexCoxde}; text-align: center;"><br></div>`);
                        }

                        thisSection += "</div>"
                        $("#colorgrid").append(thisSection);

                    }

                    //Bind events to change the color for preview
                    let previousColorCode = {};
                    $(".colorpallete").on({
                        mouseover: function() {
                            event.preventDefault();
                            $(this).animate({opacity: 0.25}, 100);

                            //Save the current color
                            var thisColorCode = $(this).attr("hex");
                            var parentDocument = parent.window.document;
                            previousColorCode["floatWindow"] = $(parentDocument).find(".floatWindow .controls").css("background-color");
                            previousColorCode["statusbar"] =  $(parentDocument).find("#statusbar").css("background-color");
                            previousColorCode["navimenu"] =  $(parentDocument).find("#navimenu").css("background-color");

                            //Set the preview color
                            if (ao_module_virtualDesktop){
                                $(parentDocument).find(".floatWindow .controls").css("background-color",hexToRgbA(thisColorCode, 0.25));
                                $(parentDocument).find("#statusbar").css("background-color",thisColorCode );
                                $(parentDocument).find("#navimenu").css("background-color",hexToRgbA(thisColorCode, 0.5));
                            }
                        },
                        mouseout: function() {
                            event.preventDefault();
                            $(this).animate({opacity: 1}, 100);
                            $(".themeColorSolid").css("background-color", "");

                            //Restore the original color
                            var parentDocument = parent.window.document;
                            if (ao_module_virtualDesktop && !cancelColorRestore){
                                $(parentDocument).find(".floatWindow .controls").css("background-color",previousColorCode["floatWindow"]);
                                $(parentDocument).find("#statusbar").css("background-color",previousColorCode["statusbar"]);
                                $(parentDocument).find("#navimenu").css("background-color",previousColorCode["navimenu"]);
                            }else if (cancelColorRestore){
                                cancelColorRestore = false;
                            }
                           
                        }
                    });

                    //Setting the current theme
                    $(".colorpallete").on("click", function(){
                        var colorCode = $(this).attr("hex");
                        writePreference("themecolor",colorCode, function(data){
                            if (data.error != undefined){
                                alert(data.error);
                            }

                            //Tick the current using color
                            tickTheCurrentSelectedThemeColor();

                            //Update the desktop theme color
                            if (ao_module_virtualDesktop){
                                cancelColorRestore=true;
                                parent.setThemeColor(colorCode);
                            }
                            
                        });
                    });

                    tickTheCurrentSelectedThemeColor();
                });
            }

            function restoreDefaultThemeColor(){
                $.ajax({
                    url: "../../system/file_system/preference",
                    data: {key: "themecolor", remove: true},
                    success: function(data){
                        if (data.error !== undefined){
                            console.log(data.error);
                        }else{
                            if (ao_module_virtualDesktop){
                                //Just emulate the restored effect first, 
                                //The theme color will restore after refresh
                                parent.setThemeColor("#262626");
                            }
                        }
                    }
                });
            }

            function tickTheCurrentSelectedThemeColor(){
                //Tick the one that is currently using
                readPreference("themecolor", function(data){
                    if (data.error == undefined){
                        //See if there is a colorpallete match the hex string
                        $(".colorpallete").each(function(){
                            if ($(this).attr("hex") == data){
                                //This is the pallete to tick
                                $(this).html(`<i style="color:white; margin-left: -4px;" class="checkmark icon"></i>`);
                            }else{
                                $(this).html(`<br>`);
                            }
                        })
                    }
                })
            }

            function readPreference(key, callback=undefined){
                $.ajax({
                    url: "../../system/desktop/preference",
                    data: {preference: key},
                    method: "POST",
                    success: function(data){
                        if (callback != undefined){
                            callback(data);
                        }
                    }
                });
            }

            function writePreference(key, value, callback=undefined){
                $.ajax({
                    url: "../../system/desktop/preference",
                    data: {preference: key, value: value},
                    method: "POST",
                    success: function(data){
                        if (callback != undefined){
                            callback(data);
                        }
                    }
                })
            }

            function hexToRgbA(hex, transparent=1){
                var c;
                if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
                    c= hex.substring(1).split('');
                    if(c.length== 3){
                        c= [c[0], c[0], c[1], c[1], c[2], c[2]];
                    }
                    c= '0x'+c.join('');
                    return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+',' + transparent + ')';
                }
                throw new Error('Bad Hex');
            }

            function applyWallpaper(){
                var targetWallpaper =JSON.parse(decodeURIComponent($("#wallpaperlist").val()));
                $.get("../../system/desktop/theme?set=" + targetWallpaper.Theme, function(data) {
                    if (ao_module_virtualDesktop == true){
                        parent.changeDesktopTheme(targetWallpaper.Theme);
                    }
                    if (data.includes("Error")) {
                        console.log(data);
                        return;
                    }

                    //Reload the preview
                    initCurrentBackgroundPreview();

                    //Show change finsihed
                    $("#wallpaperChangeConfirm").slideDown('fast').delay(3000).slideUp('fast');
                });
            }
        </script>
    </body>
</html>